package cn.tedu.note.web;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.tedu.note.entity.User;
import cn.tedu.note.service.NameException;
import cn.tedu.note.service.PasswordException;
import cn.tedu.note.service.UserService;
import cn.tedu.note.util.JsonResult;

@Controller
@RequestMapping("/user")
public class UserController
	extends AbstractController{
	
	@Resource
	private UserService userService;
	
	@ResponseBody
	@RequestMapping("/login.do")
	public Object login(String name, 
			String password,
			HttpServletResponse res){
		//将Cookie从服务器下发的客户端
		Cookie cookie=new Cookie("token",
				"12345");
		cookie.setPath("/"); 
		User user=userService.login(
			name, password);
		//将用户表中的token下发到浏览器中
		cookie.setValue(user.getToken());
		
		res.addCookie(cookie); 
		return new JsonResult(user);
	}
	
	@RequestMapping("/regist.do")
	@ResponseBody
	public JsonResult regist(
			String name, 
			String password,
			String confirm, 
			String nick){
		User user=userService.regist(
			name, nick, password, confirm);
		return new JsonResult(user); 
	}
	
	
	@ExceptionHandler(NameException.class)
	@ResponseBody
	public Object nameexp(NameException e){
		e.printStackTrace();
		return new JsonResult(2, e);
	}
	
	@ExceptionHandler(PasswordException.class)
	@ResponseBody
	public Object pwdexp(PasswordException e){
		e.printStackTrace();
		return new JsonResult(3, e);
	}
 
}










